/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webaccess.retailws.Action;

import com.webaccess.retailws.Bean.MailBean;
import com.webaccess.retailws.Bean.UserAddressBean;
import com.webaccess.retailws.Bean.UserInfoBean;
import com.webaccess.retailws.Delegate.CategoryDelegate;
import com.webaccess.retailws.Delegate.MailDelegate;
import com.webaccess.retailws.Delegate.UserInfoDelegate;
import com.webaccess.retailws.Util.CategoryUtil;
import com.webaccess.retailws.Util.CommonUtil;
import com.webaccess.retailws.Util.EncryptDecryptUtil;
import com.webaccess.retailws.Util.RandomPasswordUtil;
import com.webaccess.retailws.Util.SendMailUtil;
import com.webaccess.retailws.Util.UserAccountUtil;
import java.util.LinkedHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;

/**
 *
 * @author Owner
 */
public class UserAccountDispatchAction extends DispatchAction {

    /* forward name="success" path="" */
    private String SUCCESS = "success";
    UserInfoDelegate userDelegate = null;
    EncryptDecryptUtil passwordEDUtil = null;
    RandomPasswordUtil randomPassword = null;
    SendMailUtil mailUtil = null;
    CategoryUtil categUtil = new CategoryUtil();
    CommonUtil commUtil = new CommonUtil();
    UserAccountUtil userAccUtil = null;
    UserInfoBean userBean = null;
    UserAddressBean userAddrBean = null;
    ActionMessages errors = null;
    StringBuffer myQuery = null;
    MailBean mailInfo = null;
    MailDelegate mailDelegateObj = null;
    CategoryDelegate categDelegate = new CategoryDelegate();

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    public ActionForward signInGuest(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        HttpSession loginSession = request.getSession(true);
        try {
            commUtil.getTopRightListMap(request);
            DynaActionForm guestSignInForm = (DynaActionForm) form;
            loginSession.setAttribute("guestEmail", guestSignInForm.getString("guestEmail"));
            SUCCESS ="checkoutguestaddr";
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward checkoutSignIn(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userAddrBean = new UserAddressBean();
        userDelegate = new UserInfoDelegate();
        userBean = new UserInfoBean();
        HttpSession loginSession = request.getSession(true);

        try {
            commUtil.getTopRightListMap(request);
            Long userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            Long roleId = Long.parseLong(loginSession.getAttribute("loginRoleId").toString());
            if (userId > 0 && roleId > 0) {
                userBean = userDelegate.getUserInfo(userId, roleId);
                request.setAttribute("userDetail", userBean);
            } else if (userId > 0 && roleId == 0) {
                request.setAttribute("guestEmail", loginSession.getAttribute("guestEmail"));
            }
            SUCCESS = "checkoutsigninshow";
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward checkOut(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userAddrBean = new UserAddressBean();
        userDelegate = new UserInfoDelegate();
        HttpSession loginSession = request.getSession(true);

        try {
            commUtil.getTopRightListMap(request);
            Long userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            Long roleId = Long.parseLong(loginSession.getAttribute("loginRoleId").toString());
            if (userId > 0 && roleId > 0) {
                UserAddressBean[] userAddrList = userDelegate.getUserAddress(userId);
                request.setAttribute("userAddrBilling", userAddrList[0]);
                request.setAttribute("userAddrDelivery", userAddrList[1]);
                loginSession.setAttribute("addressId", userAddrList[1].getAddressId());

                request.setAttribute("titleMap", userDelegate.getTitleLHMap());
                request.setAttribute("stateMap", userDelegate.getStateLHMap());
                SUCCESS = "showcheckoutaddr";
            } else {
                SUCCESS = "showcheckoutsignin";
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward deleteUserInfo(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        Long userId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            userId = Long.parseLong(request.getParameter("userId"));

            boolean isUserDeleted = userDelegate.deleteUser(userId);
            if (isUserDeleted == true) {
                SUCCESS = "userinfosuccess";
            } else {
                SUCCESS = "deleteuserinfofailure";
            }
        } catch (Exception ex) {
            SUCCESS = "deleteuserinfofailure";
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showManageUsers(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();

        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            UserInfoBean[] userBeanList = userDelegate.getAllUsers(1);
            request.setAttribute("userList", userBeanList);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "manageusershow";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showEditUserInfo(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userBean = new UserInfoBean();
        userDelegate = new UserInfoDelegate();
        HttpSession loginSession = request.getSession(true);
        Long userId = 0L, roleId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            request.setAttribute("titleMap", userDelegate.getTitleLHMap());
            request.setAttribute("stateMap", userDelegate.getStateLHMap());

            userId = Long.parseLong(request.getParameter("userId"));
            roleId = Long.parseLong(loginSession.getAttribute("loginRoleId").toString());
            userBean = userDelegate.getUserInfo(userId, roleId);
            request.setAttribute("userInfo", userBean);

            UserAddressBean[] userAddrList = userDelegate.getUserAddress(userId);
            request.setAttribute("userAddressBill", userAddrList[0]);
            request.setAttribute("userAddressDel", userAddrList[1]);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "editusershow";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward insertUserInfo(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        userAccUtil = new UserAccountUtil();
        errors = new ActionMessages();

        int prefixId = 0, billingStateId = 0, deliveryStateId = 0, newsLetter = 0;
        String prefix = "", firstName = "", lastName = "", middleName = "", profession = "", emailId = "", mobileNo = "", dateOfBirth = "", username = "", password = "", confirmPassword = "", answer = "";
        Long securityQuestionId = 0L;
        String billingHouse = "", billingStreet = "", billingCity = "", billingState = "", billingContact = "", billingPinCode = "", deliveryHouse = "", deliveryStreet = "", deliveryCity = "", deliveryState = "", deliveryContact = "", deliveryPinCode = "";
        try {
            commUtil.getTopRightListMap(request);
            DynaActionForm userDynaFormObj = (DynaActionForm) form;

            if (isTokenValid(request)) {

                prefixId = Integer.parseInt(request.getParameter("prefix"));
                prefix = userDelegate.getPrefix(prefixId);
                firstName = String.valueOf(userDynaFormObj.get("firstName")).trim();
                middleName = String.valueOf(userDynaFormObj.get("middleName")).trim();
                lastName = String.valueOf(userDynaFormObj.get("lastName")).trim();
                profession = String.valueOf(userDynaFormObj.get("profession")).trim();
                emailId = String.valueOf(userDynaFormObj.get("emailId")).trim();
                mobileNo = String.valueOf(userDynaFormObj.get("mobileNo")).trim();
                dateOfBirth = userAccUtil.formatStringDate(userDynaFormObj.get("dateOfBirth").toString());
                if ((Boolean) userDynaFormObj.get("newsLetter") == true) {
                    newsLetter = 1;
                }
                username = String.valueOf(userDynaFormObj.get("userName")).trim();
                password = String.valueOf(userDynaFormObj.get("password")).trim();
                confirmPassword = String.valueOf(userDynaFormObj.get("confirmPassword")).trim();
                securityQuestionId = Long.parseLong(request.getParameter("securityQuestion"));
                answer = String.valueOf(userDynaFormObj.get("answer")).trim();
                billingHouse = String.valueOf(userDynaFormObj.get("billingHouse")).trim();
                billingStreet = String.valueOf(userDynaFormObj.get("billingStreet")).trim();
                billingCity = String.valueOf(userDynaFormObj.get("billingCity")).trim();
                billingStateId = Integer.parseInt(request.getParameter("billingState"));
                billingState = userDelegate.getState(billingStateId);
                billingPinCode = String.valueOf(userDynaFormObj.get("billingPinCode")).trim();
                billingContact = String.valueOf(userDynaFormObj.get("billingContact")).trim();

                if ((Boolean) userDynaFormObj.get("sameBillingAddr") == true) {
                    deliveryHouse = String.valueOf(userDynaFormObj.get("billingHouse")).trim();
                    deliveryStreet = String.valueOf(userDynaFormObj.get("billingStreet")).trim();
                    deliveryCity = String.valueOf(userDynaFormObj.get("billingCity")).trim();
                    billingStateId = Integer.parseInt(request.getParameter("billingState"));
                    deliveryState = userDelegate.getState(billingStateId);
                    deliveryPinCode = String.valueOf(userDynaFormObj.get("billingPinCode")).trim();
                    deliveryContact = String.valueOf(userDynaFormObj.get("billingContact")).trim();
                } else {
                    deliveryHouse = String.valueOf(userDynaFormObj.get("deliveryHouse")).trim();
                    deliveryStreet = String.valueOf(userDynaFormObj.get("deliveryStreet")).trim();
                    deliveryCity = String.valueOf(userDynaFormObj.get("deliveryCity")).trim();
                    deliveryStateId = Integer.parseInt(request.getParameter("deliveryState"));
                    deliveryState = userDelegate.getState(deliveryStateId);
                    deliveryPinCode = String.valueOf(userDynaFormObj.get("deliveryPinCode")).trim();
                    deliveryContact = String.valueOf(userDynaFormObj.get("deliveryContact")).trim();
                }

                Pattern numericExp = Pattern.compile("/^[0-9]+$/");
                Pattern alphaExp = Pattern.compile("/^[a-zA-Z]+$/");
                Pattern emailExp = Pattern.compile("/^[\\w\\-\\.\\+]+\\@[a-zA-Z0-9\\.\\-]+\\.[a-zA-z0-9]{2,4}$/");

                Matcher matchFirstName = alphaExp.matcher(firstName);
                Matcher matchMiddleName = alphaExp.matcher(middleName);
                Matcher matchLastName = alphaExp.matcher(lastName);
                Matcher matchProfession = alphaExp.matcher(profession);
                Matcher matchEmailId = emailExp.matcher(emailId);
                Matcher matchMobileNo = numericExp.matcher(mobileNo.toString());
                Matcher matchBillingCity = alphaExp.matcher(billingCity);
                Matcher matchBillingPinCode = numericExp.matcher(billingPinCode.toString());
                Matcher matchBillingContact = numericExp.matcher(billingContact.toString());
                Matcher matchDeliveryCity = alphaExp.matcher(deliveryCity);
                Matcher matchDeliveryPinCode = numericExp.matcher(deliveryPinCode.toString());
                Matcher matchDeliveryContact = numericExp.matcher(deliveryContact.toString());

                if (prefixId == 0 || firstName.equalsIgnoreCase("") || lastName.equalsIgnoreCase("") || emailId.equalsIgnoreCase("") || dateOfBirth.equalsIgnoreCase("") || mobileNo.equalsIgnoreCase("")) {
                    errors.add("errRegisterPI", new ActionMessage("errors.registerpi.required"));
                } else if (matchFirstName.find()) {
                    errors.add("errFirstName", new ActionMessage("errors.fname.invalid"));
                } else if (matchMiddleName.find()) {
                    errors.add("errMiddleName", new ActionMessage("errors.mname.invalid"));
                } else if (matchLastName.find()) {
                    errors.add("errLastName", new ActionMessage("errors.lname.invalid"));
                } else if (matchProfession.find()) {
                    errors.add("errProfession", new ActionMessage("errors.profession.invalid"));
                } else if (matchEmailId.find()) {
                    errors.add("errEmailId", new ActionMessage("errors.emailid.invalid"));
                } else if (userDelegate.checkEmail(emailId)) {
                    errors.add("errEmailId", new ActionMessage("errors.emailid.exists"));
                } else if (matchMobileNo.find()) {
                    errors.add("errMobileNo", new ActionMessage("errors.mobileno.invalid"));
                } else if (mobileNo.toString().length() < 10 || mobileNo.toString().length() > 10) {
                    errors.add("errMobileNo", new ActionMessage("errors.mobileno.valid"));
                } else if (securityQuestionId == 0 || answer.equalsIgnoreCase("") || username.equalsIgnoreCase("") || password.equalsIgnoreCase("") || confirmPassword.equalsIgnoreCase("")) {
                    errors.add("errRegisterLI", new ActionMessage("errors.registerli.required"));
                } else if (username.length() <= 6 || username.length() >= 15) {
                    errors.add("errUsername", new ActionMessage("errors.username.invalid"));
                } else if (userDelegate.checkUsername(username)) {
                    errors.add("errUsername", new ActionMessage("errors.username.exists"));
                } else if (password.length() <= 6) {
                    errors.add("errPassword", new ActionMessage("errors.password.invalid"));
                } else if (billingHouse.equalsIgnoreCase("") || billingStreet.equalsIgnoreCase("") || billingCity.equalsIgnoreCase("") || billingPinCode.equalsIgnoreCase("") || billingStateId == 0 || billingContact.equalsIgnoreCase("")) {
                    errors.add("errRegisterBAI", new ActionMessage("errors.registerbai.required"));
                } else if (matchBillingCity.find()) {
                    errors.add("errBillingCity", new ActionMessage("errors.billingcity.invalid"));
                } else if (matchBillingPinCode.find()) {
                    errors.add("errBillingPinCode", new ActionMessage("errors.billingpincode.invalid"));
                } else if (matchBillingContact.find()) {
                    errors.add("errBillingContact", new ActionMessage("errors.billingcontact.invalid"));
                } else if ((Boolean) userDynaFormObj.get("sameBillingAddr") == false) {
                    if (deliveryHouse.equalsIgnoreCase("") || deliveryStreet.equalsIgnoreCase("") || deliveryCity.equalsIgnoreCase("") || deliveryPinCode.equalsIgnoreCase("") || deliveryStateId == 0 || deliveryContact.equalsIgnoreCase("")) {
                        errors.add("errRegisterDAI", new ActionMessage("errors.registerdai.required"));
                    } else if (matchDeliveryCity.find()) {
                        errors.add("errDeliveryCity", new ActionMessage("errors.deliverycity.invalid"));
                    } else if (matchDeliveryPinCode.find()) {
                        errors.add("errDeliveryPinCode", new ActionMessage("errors.deliverypincode.invalid"));
                    } else if (matchDeliveryContact.find()) {
                        errors.add("errDeliveryContact", new ActionMessage("errors.deliverycontact.invalid"));
                    } else {
                        SUCCESS = userAccUtil.saveUserInfo(prefix, firstName, middleName, lastName, profession, emailId, mobileNo, dateOfBirth,
                                newsLetter, securityQuestionId, answer, username, password, billingHouse, billingStreet, billingCity, billingState,
                                billingPinCode, billingContact, deliveryHouse, deliveryStreet, deliveryCity, deliveryPinCode, deliveryState, deliveryContact);
                    }
                } else {
                    SUCCESS = userAccUtil.saveUserInfo(prefix, firstName, middleName, lastName, profession, emailId, mobileNo, dateOfBirth,
                            newsLetter, securityQuestionId, answer, username, password, billingHouse, billingStreet, billingCity, billingState,
                            billingPinCode, billingContact, deliveryHouse, deliveryStreet, deliveryCity, deliveryPinCode, deliveryState, deliveryContact);
                }
                resetToken(request);
                saveErrors(request, errors);
                if (errors.isEmpty()) {
                    SUCCESS = "registersuccess";
                } else {
                    SUCCESS = "registerfailure";
                }
            }
            saveToken(request);

        } catch (Exception ex) {
            SUCCESS = "registerfailure";
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showUserRegistration(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        userDelegate = new UserInfoDelegate();
        try {
            commUtil.getTopRightListMap(request);

            LinkedHashMap titleMap = userDelegate.getTitleLHMap();
            request.setAttribute("titleMap", titleMap);

            LinkedHashMap stateMap = userDelegate.getStateLHMap();
            request.setAttribute("stateMap", stateMap);

            LinkedHashMap securityQuestionMap = userDelegate.getSecurityQuestionLHMap();
            request.setAttribute("securityQuestionMap", securityQuestionMap);

            saveToken(request);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "showregistration";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showUserLogin(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        commUtil.getTopRightListMap(request);
        SUCCESS = "showlogin";
        return mapping.findForward(SUCCESS);
    }

    public ActionForward showNewsletter(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        userBean = new UserInfoBean();
        HttpSession loginSession = request.getSession(true);
        Long userId = 0L, roleId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            roleId = Long.parseLong(loginSession.getAttribute("loginRoleId").toString());
            userBean = userDelegate.getUserInfo(userId, roleId);
            request.setAttribute("userInfoBean", userBean);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "shownewsletter";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward editNewsletter(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        userBean = new UserInfoBean();
        mailUtil = new SendMailUtil();
        mailDelegateObj = new MailDelegate();
        commUtil = new CommonUtil();

        DynaActionForm nlDynaFormObj = (DynaActionForm) form;
        HttpSession loginSession = request.getSession(true);
        Long userId = 0L, roleId = 0L;
        int newsLetter = 0;

        try {
            commUtil.getTopRightListMap(request);
            userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            roleId = Long.parseLong(loginSession.getAttribute("loginRoleId").toString());
            if ((Boolean) nlDynaFormObj.get("newsLetter") == true) {
                newsLetter = 1;
            }

            boolean newsletterChanged = userDelegate.saveNewsletter(userId, newsLetter);
            if (newsletterChanged == true) {
                userBean = userDelegate.getUserInfo(userId, roleId);
                StringBuffer messageBody = new StringBuffer();
                messageBody.append("Hello ");
                messageBody.append(userBean.getFullName());
                messageBody.append("\n");

                if (newsLetter == 0) {
                    messageBody.append("Your have successfully unsubscribed from general Newsletters.");
                } else {
                    messageBody.append("Your have successfully subscribed for general Newsletters.");
                }
                messageBody.append("\n");
                messageBody.append("Thank You.");

                mailInfo = new MailBean();
                mailInfo.setFromAddress("abhishek.agrawal@webaccess.co.in");
                mailInfo.setToAddress(userBean.getEmailId());
                mailInfo.setMsgSubject("E Shop - Newsletter");
                mailInfo.setMsgContent(messageBody.toString());
                mailInfo.setMsgDateTime(commUtil.getCurrentDateTime());
                mailInfo.setUserId(userId);
                mailInfo.setPurpose("Newsletter");
                Long mailId = mailDelegateObj.saveMailInfo(mailInfo);
                if (mailId > 0) {
                    mailUtil.sendMail(mailInfo.getFromAddress(), mailInfo.getToAddress(), mailInfo.getMsgSubject(), mailInfo.getMsgContent());
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "showacctdashboard";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showEditUserPersonalInfo(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        userBean = new UserInfoBean();
        HttpSession loginSession = request.getSession(true);
        Long userId = 0L, roleId = 0L;
        String changePassword = "";
        try {
            commUtil.getTopRightListMap(request);
            LinkedHashMap titleMap = userDelegate.getTitleLHMap();
            request.setAttribute("titleMap", titleMap);

            changePassword = request.getParameter("changePassword");
            userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            roleId = Long.parseLong(loginSession.getAttribute("loginRoleId").toString());
            userBean = userDelegate.getUserInfo(userId, roleId);
            userBean.setChangePassword(changePassword);
            request.setAttribute("userInfoBean", userBean);

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "showeditaccount";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showAddress(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        HttpSession loginSession = request.getSession(true);
        Long userId = 0L, addressId = 0L;
        int addressTypeId = 0;
        try {
            commUtil.getTopRightListMap(request);
            LinkedHashMap titleMap = userDelegate.getTitleLHMap();
            request.setAttribute("titleMap", titleMap);

            LinkedHashMap stateMap = userDelegate.getStateLHMap();
            request.setAttribute("stateMap", stateMap);

            addressTypeId = Integer.parseInt(request.getParameter("addrTypeId"));
            userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            UserAddressBean[] userAddrBean = userDelegate.selectAddressByType(userId, addressTypeId);
            loginSession.setAttribute("addressId", userAddrBean[0].getAddressId());
            request.setAttribute("userAddrInfo", userAddrBean[0]);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "showeditaddress";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward editAddress(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        userAccUtil = new UserAccountUtil();
        HttpSession loginSession = request.getSession(true);
        int editPrefixId = 0, editStateId = 0;
        String editPrefix = "", editFirstName = "", editLastName = "", editMiddleName = "", editHouse = "", editStreet = "", editCity = "", editState = "", editContact = "", editPinCode = "";
        Long userId = 0L, addressId = 0L;
        int addressTypeId = 0;
        try {
            commUtil.getTopRightListMap(request);
            DynaActionForm userDynaFormObj = (DynaActionForm) form;
            userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            addressId = Long.parseLong(loginSession.getAttribute("addressId").toString());
            editPrefixId = Integer.parseInt(request.getParameter("titleId"));
            editPrefix = userDelegate.getPrefix(editPrefixId);
            editFirstName = String.valueOf(request.getParameter("addrFirstName")).trim();
            editMiddleName = String.valueOf(request.getParameter("addrMiddleName")).trim();
            editLastName = String.valueOf(request.getParameter("addrLastName")).trim();
            editHouse = String.valueOf(request.getParameter("house")).trim();
            editStreet = String.valueOf(request.getParameter("street")).trim();
            editCity = String.valueOf(request.getParameter("city")).trim();
            editStateId = Integer.parseInt(request.getParameter("stateId"));
            editState = userDelegate.getState(editStateId);
            editPinCode = String.valueOf(request.getParameter("pinCode")).trim();
            editContact = String.valueOf(request.getParameter("contact")).trim();

            Pattern numericExp = Pattern.compile("/^[0-9]+$/");
            Pattern alphaExp = Pattern.compile("/^[a-zA-Z]+$/");

            Matcher matchFirstName = alphaExp.matcher(editFirstName);
            Matcher matchMiddleName = alphaExp.matcher(editMiddleName);
            Matcher matchLastName = alphaExp.matcher(editLastName);
            Matcher matchCity = alphaExp.matcher(editCity);
            Matcher matchPinCode = numericExp.matcher(editPinCode.toString());
            Matcher matchContact = numericExp.matcher(editContact.toString());

            if (editPrefixId == 0 || editFirstName.equalsIgnoreCase("") || editLastName.equalsIgnoreCase("")) {
                errors.add("errEditAddress", new ActionMessage("errors.editaddress.required"));
            } else if (matchFirstName.find()) {
                errors.add("errFirstName", new ActionMessage("errors.fname.invalid"));
            } else if (matchMiddleName.find()) {
                errors.add("errMiddleName", new ActionMessage("errors.mname.invalid"));
            } else if (matchLastName.find()) {
                errors.add("errLastName", new ActionMessage("errors.lname.invalid"));
            } else if (editHouse.equalsIgnoreCase("") || editStreet.equalsIgnoreCase("") || editCity.equalsIgnoreCase("") || editPinCode.equalsIgnoreCase("") || editStateId == 0 || editContact.equalsIgnoreCase("")) {
                errors.add("errEditAddress", new ActionMessage("errors.editaddress.required"));
            } else if (matchCity.find()) {
                errors.add("errCity", new ActionMessage("errors.city.invalid"));
            } else if (matchPinCode.find()) {
                errors.add("errPinCode", new ActionMessage("errors.pincode.invalid"));
            } else if (matchContact.find()) {
                errors.add("errContact", new ActionMessage("errors.contact.invalid"));
            } else {
                SUCCESS = userAccUtil.saveAddressInfo(userId, addressId, editPrefix, editFirstName, editMiddleName, editLastName, editHouse, editStreet, editCity, editPinCode, editState, editContact);
            }
            saveErrors(request, errors);
            if (errors.isEmpty()) {
                SUCCESS = "showacctdashboard";
            } else {
                SUCCESS = "showeditaddress";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showManageAddress(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        HttpSession loginSession = request.getSession(true);
        DynaActionForm addressDynaForm = (DynaActionForm) form;
        Long userId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            UserAddressBean[] userAddrList = userDelegate.getUserAddress(userId);
            request.setAttribute("userAddressInfo", userAddrList);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "showmanageaddress";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showAccountDashboard(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        userBean = new UserInfoBean();

        HttpSession loginSession = request.getSession(true);
        Long userId = 0L, roleId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            roleId = Long.parseLong(loginSession.getAttribute("loginRoleId").toString());
            userBean = userDelegate.getUserInfo(userId, roleId);
            UserAddressBean[] userAddrList = userDelegate.getUserAddress(userId);

            request.setAttribute("userInfo", userBean);
            request.setAttribute("userAddressInfo", userAddrList);

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            SUCCESS = "showaccountinfo";
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward showForgotPassword(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        commUtil.getTopRightListMap(request);
        LinkedHashMap securityQuestionMap = userDelegate.getSecurityQuestionLHMap();
        request.setAttribute("securityQuestionMap", securityQuestionMap);

        SUCCESS = "showforgotpassword";
        return mapping.findForward(SUCCESS);
    }

    public ActionForward logout(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        Long userId = 0L, userLogStatusId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            HttpSession loginSession = request.getSession(true);
            if (loginSession.getAttribute("logStatusId") != null) {
                userLogStatusId = Long.parseLong(loginSession.getAttribute("logStatusId").toString());
                userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
                userDelegate.userLog(userLogStatusId, userId, null);
            }
            loginSession = request.getSession(false);
            if (loginSession.getAttribute("loginUserId") != null) {
                if (loginSession != null) {
                    loginSession.removeAttribute("loginUserId");
                    loginSession.invalidate();
                    SUCCESS = "logoutsuccess";
                }
            } else {
                SUCCESS = "logoutfailure";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward forgotPassword(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        randomPassword = new RandomPasswordUtil();
        passwordEDUtil = new EncryptDecryptUtil();
        userBean = new UserInfoBean();
        mailUtil = new SendMailUtil();
        mailDelegateObj = new MailDelegate();
        commUtil = new CommonUtil();
        userAccUtil = new UserAccountUtil();
        errors = new ActionMessages();
        String emailId = null, answer = null, dbAnswer = null, randomPasswordStr = null, encryptRandomPassword;
        Long securityQuestionId = 0L, dbSecurityQuestionId = 0L, userId = 0L, roleId = 0L;
        boolean isEmailExist = false;
        try {
            commUtil.getTopRightListMap(request);
            emailId = String.valueOf(request.getParameter("emailId"));
            securityQuestionId = Long.parseLong(request.getParameter("securityQuestion"));
            answer = String.valueOf(request.getParameter("answer")).trim();
            isEmailExist = userDelegate.checkEmail(emailId);
            if (emailId.equalsIgnoreCase("") || securityQuestionId == 0 || answer.equalsIgnoreCase("")) {
                errors.add("errForgotPassword", new ActionMessage("errors.forgotpassword.required"));
            } else if (isEmailExist == false) {
                errors.add("errEmail", new ActionMessage("errors.emailid.notexist"));
            } else {
                userBean = userDelegate.getUserSecurityQuestion(emailId);
                userId = userBean.getUserId();
                dbSecurityQuestionId = userBean.getSecurityQuestionId();
                dbAnswer = userBean.getAnswer();
                roleId = userBean.getRoleId();
                if (securityQuestionId == dbSecurityQuestionId && answer.equals(dbAnswer)) {
                    randomPasswordStr = randomPassword.generateRandomPassword();
                    encryptRandomPassword = EncryptDecryptUtil.encrypt(randomPasswordStr);
                    boolean passwordChanged = userDelegate.changePassword(userId, encryptRandomPassword);
                    if (passwordChanged == true) {
                        userBean = userDelegate.getUserInfo(userId, roleId);
                        StringBuffer messageBody = new StringBuffer();
                        messageBody.append("Hello ");
                        messageBody.append(userBean.getFullName());
                        messageBody.append("\n");
                        messageBody.append("Your Password has been reset.");
                        messageBody.append("\n");
                        messageBody.append("Your New Password");
                        messageBody.append("\n");
                        messageBody.append("Password :");
                        messageBody.append(randomPasswordStr);
                        messageBody.append("\n");
                        messageBody.append("Thank You.");

                        mailInfo = new MailBean();
                        mailInfo.setFromAddress("abhishek.agrawal@webaccess.co.in");
                        mailInfo.setToAddress(emailId);
                        mailInfo.setMsgSubject("E Shop - Password Reset");
                        mailInfo.setMsgContent(messageBody.toString());
                        mailInfo.setMsgDateTime(commUtil.getCurrentDateTime());
                        mailInfo.setUserId(userId);
                        mailInfo.setPurpose("Forgot Password");
                        Long mailId = mailDelegateObj.saveMailInfo(mailInfo);
                        if (mailId > 0) {
                            mailUtil.sendMail(mailInfo.getFromAddress(), mailInfo.getToAddress(), mailInfo.getMsgSubject(), mailInfo.getMsgContent());
                        }
                    }
                } else {
                    errors.add("errSecurityQuestion", new ActionMessage("errors.securityquestion.notexist"));
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            saveErrors(request, errors);
            if (errors.isEmpty()) {
                SUCCESS = "showlogin";
            } else {
                SUCCESS = "forgotpasswordfailure";
            }
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward loginUserAccount(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        userDelegate = new UserInfoDelegate();
        passwordEDUtil = new EncryptDecryptUtil();
        userBean = new UserInfoBean();
        errors = new ActionErrors();
        String encryptedPassword = null;
        String actionPath = "";

        HttpSession loginSession = request.getSession(true);
        String loginUsername = null, loginPassword = null, userPassword = null, fullName = null;
        Long userId = 0L, roleId = 0L, userLogStatusId = 0L;

        try {
//        loginUsername = userDynaFormObj.get("userName").toString().trim();
//        loginPassword = userDynaFormObj.get("password").toString().trim();
            commUtil.getTopRightListMap(request);

            loginUsername = String.valueOf(request.getParameter("userName"));
            loginPassword = String.valueOf(request.getParameter("password"));

            if (loginUsername.equalsIgnoreCase("") || loginPassword.equalsIgnoreCase("")) {
                errors.add("errLogin", new ActionMessage("errors.login.failed"));
            } else if (loginUsername.equalsIgnoreCase("")) {
                errors.add("errUsername", new ActionMessage("errors.username.required"));
            } else if (loginPassword.equalsIgnoreCase("")) {
                errors.add("errPassword", new ActionMessage("errors.password.required"));
            } else {
                userBean = userDelegate.getLoginPassword(loginUsername);
                encryptedPassword = userBean.getPassword();
                userId = userBean.getUserId();
                roleId = userBean.getRoleId();
                fullName = userBean.getFullName();
                //System.out.println(loginSession.getAttribute("loginUserId"));
                loginSession.setAttribute("loginUserId", userId);
                loginSession.setAttribute("loginRoleId", roleId);
                loginSession.setAttribute("loginName", fullName);
                //Decrypt the user password (retrived from db) here   
                if (encryptedPassword != null) {
                    userPassword = EncryptDecryptUtil.decrypt(encryptedPassword);
                    if (!loginPassword.equals(userPassword)) {
                        errors.add("errLogin", new ActionMessage("errors.loginpassword.invalid"));
                    } else {
                        String ipaddress = request.getRemoteAddr();
                        userLogStatusId = userDelegate.userLog(0L, userId, ipaddress);
                        loginSession.setAttribute("loginUsername", loginUsername);
                        loginSession.setAttribute("logStatusId", userLogStatusId);
                    }
                } else {
                    errors.add("errLogin", new ActionMessage("errors.loginusername.invalid"));
                }
            }
            if (roleId == 1) {
                actionPath = "showacctdashboard";
            } else if (roleId == 2) {
                actionPath = "showadminhome";
            }
        } catch (Exception ex) {
            SUCCESS = "loginfailure";
            ex.printStackTrace();
        } finally {
            saveErrors(request, errors);

            if (errors.isEmpty()) {
                SUCCESS = actionPath;
            } else {
                SUCCESS = "loginfailure";
            }
            return mapping.findForward(SUCCESS);
        }
    }

    /**
     *
     *     public ActionForward updateUserInfo(ActionMapping mapping, ActionForm form,
     *           HttpServletRequest request, HttpServletResponse response)
     *           throws Exception {
     *       userDelegate = new UserInfoDelegate();
     *       userBean = new UserInfoBean();
     *       userAccUtil = new UserAccountUtil();
     *       DynaActionForm userDynaFormObj = (DynaActionForm) form;
     *       errors = new ActionMessages();
     *       HttpSession loginSession = request.getSession(true);

     *       int prefixId = 0, billingStateId = 0, deliveryStateId = 0, newsLetter = 0;
     *       String prefix = "", firstName = "", lastName = "", middleName = "", profession = "", emailId = "", mobileNo = "", dateOfBirth = "", username = "", password = "", confirmPassword = "", answer = "";
     *       Long securityQuestionId = 0L;
     *       String billingHouse = "", billingStreet = "", billingCity = "", billingState = "", billingContact = "", billingPinCode = "", deliveryHouse = "", deliveryStreet = "", deliveryCity = "", deliveryState = "", deliveryContact = "", deliveryPinCode = "";
     *   }
     *
     */
    public ActionForward searchUser(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        userBean = new UserInfoBean();
        String searchUser = "";
        int userInfo = 0;
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            userInfo = Integer.parseInt(request.getParameter("userInfo"));
            searchUser = request.getParameter("searchUser");
            if (userInfo == 0) {
                SUCCESS = "userinfosuccess";
            } else if (userInfo == 1) {
                UserInfoBean[] userBeanList = userDelegate.searchUserByFirstName(searchUser);
                request.setAttribute("userList", userBeanList);
                SUCCESS = "manageusershow";
            } else if (userInfo == 2) {
                UserInfoBean[] userBeanList = userDelegate.searchUserByLastName(searchUser);
                request.setAttribute("userList", userBeanList);
                SUCCESS = "manageusershow";
            } else if (userInfo == 3) {
                UserInfoBean[] userBeanList = userDelegate.searchUserByEmail(searchUser);
                request.setAttribute("userList", userBeanList);
                SUCCESS = "manageusershow";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward searchUserByStatus(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        userBean = new UserInfoBean();
        Long userStatusId = 0L;
        try {
            commUtil.getTopRightListMap(request);
            request.setAttribute("statusList", commUtil.getStatus());
            userStatusId = Long.parseLong(request.getParameter("accountStatusId"));

            if (userStatusId > 0) {
                SUCCESS = "userinfosuccess";
            } else {
                UserInfoBean[] userBeanList = userDelegate.searchUserByStatusId(userStatusId);
                request.setAttribute("userList", userBeanList);
                SUCCESS = "manageusershow";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }

    public ActionForward editUserInfo(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        userDelegate = new UserInfoDelegate();
        userBean = new UserInfoBean();
        userAccUtil = new UserAccountUtil();
        DynaActionForm userDynaFormObj = (DynaActionForm) form;
        errors = new ActionMessages();
        HttpSession loginSession = request.getSession(true);

        Long userId = 0L, roleId = 0L;
        int prefixId = 0;
        String prefix = "", firstName = "", lastName = "", middleName = "", profession = "", emailId = "", mobileNo = "", dateOfBirth = "", currentPassword = "", newPassword = "", confirmNewPassword = "";

        try {
            commUtil.getTopRightListMap(request);
            userId = Long.parseLong(loginSession.getAttribute("loginUserId").toString());
            roleId = Long.parseLong(loginSession.getAttribute("loginRoleId").toString());
            prefixId = Integer.parseInt(request.getParameter("titleId"));
            prefix = userDelegate.getPrefix(prefixId);
            firstName = String.valueOf(userDynaFormObj.get("firstName")).trim();
            middleName = String.valueOf(userDynaFormObj.get("middleName")).trim();
            lastName = String.valueOf(userDynaFormObj.get("lastName")).trim();
            profession = String.valueOf(userDynaFormObj.get("profession")).trim();
            emailId = String.valueOf(userDynaFormObj.get("emailId")).trim();
            mobileNo = String.valueOf(userDynaFormObj.get("mobileNo")).trim();
            dateOfBirth = userAccUtil.formatStringDate(userDynaFormObj.get("dateOfBirth").toString());
            currentPassword = String.valueOf(userDynaFormObj.get("currentPassword")).trim();
            newPassword = String.valueOf(userDynaFormObj.get("newPassword")).trim();
            confirmNewPassword = String.valueOf(userDynaFormObj.get("confirmNewPassword")).trim();

            Pattern numericExp = Pattern.compile("/^[0-9]+$/");
            Pattern alphaExp = Pattern.compile("/^[a-zA-Z]+$/");
            Pattern emailExp = Pattern.compile("/^[\\w\\-\\.\\+]+\\@[a-zA-Z0-9\\.\\-]+\\.[a-zA-z0-9]{2,4}$/");
            Matcher matchFirstName = alphaExp.matcher(firstName);
            Matcher matchMiddleName = alphaExp.matcher(middleName);
            Matcher matchLastName = alphaExp.matcher(lastName);
            Matcher matchProfession = alphaExp.matcher(profession);
            Matcher matchEmailId = emailExp.matcher(emailId);
            Matcher matchMobileNo = numericExp.matcher(mobileNo.toString());

            if (prefixId == 0) {
                errors.add("errPrefix", new ActionMessage("errors.prefix.select"));
            } else if (firstName.equalsIgnoreCase("")) {
                errors.add("errFirstName", new ActionMessage("errors.fname.required"));
            } else if (matchFirstName.find()) {
                errors.add("errFirstName", new ActionMessage("errors.fname.invalid"));
            } else if (matchMiddleName.find()) {
                errors.add("errMiddleName", new ActionMessage("errors.mname.invalid"));
            } else if (lastName.equalsIgnoreCase("")) {
                errors.add("errLastName", new ActionMessage("errors.lname.required"));
            } else if (matchLastName.find()) {
                errors.add("errLastName", new ActionMessage("errors.lname.invalid"));
            } else if (matchProfession.find()) {
                errors.add("errProfession", new ActionMessage("errors.profession.invalid"));
            } else if (emailId.equals("")) {
                errors.add("errEmailId", new ActionMessage("errors.emailid.required"));
            } else if (matchEmailId.find()) {
                errors.add("errEmailId", new ActionMessage("errors.emailid.invalid"));
            } else if (dateOfBirth.equalsIgnoreCase("")) {
                errors.add("errDateOfBirth", new ActionMessage("errors.dateofbirth.required"));
            } else if (mobileNo.equalsIgnoreCase("")) {
                errors.add("errMobileNo", new ActionMessage("errors.mobileno.required"));
            } else if (matchMobileNo.find()) {
                errors.add("errMobileNo", new ActionMessage("errors.mobileno.invalid"));
            } else if (mobileNo.toString().length() < 10 || mobileNo.toString().length() > 10) {
                errors.add("errMobileNo", new ActionMessage("errors.mobileno.valid"));
            } else if ((Boolean) userDynaFormObj.get("changePassword") == true) {
                if (currentPassword.equalsIgnoreCase("")) {
                    errors.add("errCurrentPassword", new ActionMessage("errors.currentpassword.required"));
                } else if (userDelegate.checkPassword(userId, currentPassword, roleId)) {
                    if (newPassword.equalsIgnoreCase("")) {
                        errors.add("errNewPassword", new ActionMessage("errors.newpassword.required"));
                    } else if (confirmNewPassword.equalsIgnoreCase("")) {
                        errors.add("errConfirmNewPassword", new ActionMessage("errors.confirmnewpassword.required"));
                    } else if (!newPassword.equals(confirmNewPassword)) {
                        errors.add("errConfirmNewPassword", new ActionMessage("errors.confirmnewpassword.invalid"));
                    } else {
                        SUCCESS = userAccUtil.savePersonalInfo(userId, prefix, firstName, middleName, lastName, profession, emailId, dateOfBirth, mobileNo, newPassword);
                    }
                } else {
                    errors.add("errCurrentPassword", new ActionMessage("errors.currentpassword.invalid"));
                }
            } else {
                SUCCESS = userAccUtil.savePersonalInfo(userId, prefix, firstName, middleName, lastName, profession, emailId, dateOfBirth, mobileNo, newPassword);
            }
            saveErrors(request, errors);
            if (errors.isEmpty()) {
                SUCCESS = "showacctdashboard";
            } else {
                SUCCESS = "editaccountfailure";
            }
        } catch (Exception ex) {
            SUCCESS = "editaccountfailure";
            ex.printStackTrace();
        } finally {
            return mapping.findForward(SUCCESS);
        }
    }
}
